/**
 * Magic window pluing 1.0
 * Author: Mac_J@boarsoft.com
 * Need: core.js
 */
mac.window = function(self, cfg) {
	// setting tabIndex makes the div focusable
	// setting outline to 0 prevents a border on focus in Mozilla
	self.attr('tabIndex', -1).css('outline', 0);
	self.mousedown(function(e) {
		self.move2top();
	});
	var bd = self.children('.body');
	var hd = self.children('.head');
	hd.find('.icon').hover(function() {
		$(this).addClass('ui-state-hover');
	}, function() {
		$(this).removeClass('ui-state-hover');
	});
	hd.find('.closer').click(function(e) {
		if(cfg.closeAction=='remove')
			self.remove();
		else
			self.hide();
		return false;
	});
	hd.find('.pin').click(function(e) {
		self.pined = !self.pined;
		var c = 'ui-icon-pin-';
		var x = 's', y = 'w';
		if (self.pined) {
			x = 'w';
			y = 's';
		}
		$(this).removeClass(c + x).addClass(c + y);
		return false;
	});
	self.move2top = function() {
		var z = $(this).css('z-index');
		if (z != 'auto' && z >= $.ui.dialog.maxZ) {
			$.ui.dialog.maxZ = z;
		} else {
			$(this).css('z-index', ++$.ui.dialog.maxZ);
		}
		return self;
	}
	if (cfg.draggable) {
		self.draggable({
			cancel : '.body, .closer',
			handle : '.head',
			// containment: self.parent(),
			start : function() {
				if (self.pined)
					return false;
				if (cfg.onStartDrag)
					cfg.onStartDrag();
				return true;
			},
			drag : cfg.onDrag,
			stop : cfg.onStopDrag
		});
	}
	if (cfg.resizable) {
		// .ui-resizable has position: relative defined in the stylesheet
		// but dialogs have to use absolute or fixed positioning
		var p = self.css('position');
		self.resizable({
			cancel : '.body',
			// containment: self.parent(),
			// alsoResize: self.find('.body'),
			maxWidth : cfg.maxWidth,
			maxHeight : cfg.maxHeight,
			minWidth : cfg.minWidth,
			minHeight : cfg.minHeight,
			handles : cfg.handles,
			start : cfg.onStartResize,
			resize : function(){
				var h = self.height()-hd.height()-4;
				bd.height(h);
				if(cfg.onResize)
					cfg.onResize(bd.width(), h);
			},
			stop : cfg.onStopResize
		});
		self.css('position', p);
	}
	bd.height(self.height()-hd.height()-4);
	return self;
}